package colin.project.sso.server.business.observer;

import colin.project.sso.server.business.observer.enums.OperationEventEnums;
import colin.project.sso.server.business.observer.handler.AbstractOperationHandler;
import colin.project.sso.server.business.observer.handler.PermissionOperationHandler;
import colin.project.sso.server.business.observer.handler.PermissionRoleOperationHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author joker
 * @Title ServiceOperationObserver
 * @Description
 * @Date 2019/5/18 5:03 PM
 * @Since
 * @Version 1.0.0
 */
@Component
@Slf4j
public class PubOperationListener implements ApplicationListener<PubOperationEvent>, InitializingBean {

    private final List<AbstractOperationHandler> handlers = new ArrayList<>();

    @Autowired
    private PermissionOperationHandler permissionOperationHandler;

    @Autowired
    private PermissionRoleOperationHandler permissionRoleOperationHandler;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(PubOperationEvent event) {
        OperationEventEnums operationEventEnums = event.getOperationEventEnums();
        Object handleResource = event.getSource();
        //经过所有的过滤器处理
        for (AbstractOperationHandler handler : handlers) {
            handler.handleServiceOperation(operationEventEnums, handleResource);
        }


    }

    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     *
     * @throws Exception in the event of misconfiguration (such as failure to set an
     *                   essential property) or if initialization fails for any other reason
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        handlers.add(permissionOperationHandler);
        handlers.add(permissionRoleOperationHandler);
    }
}
